<!--
  智慧社区管理系统 - 批量新增费用标准对话框
  @author Wu.Liang
  @date 2025-01-30
  @description 支持多店铺选择，批量设置费用标准
-->
<template>
  <el-dialog
    v-model="visible"
    title="批量新增费用标准"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="batch-form"
    >
      <!-- 店铺选择区域 -->
      <el-form-item label="选择店铺" prop="shopIds" required>
        <div class="shop-selection-area">
          <el-select
            v-model="formData.shopIds"
            placeholder="请选择店铺（支持多选）"
            multiple
            filterable
            clearable
            :loading="loading"
            style="width: 100%"
            @change="handleShopChange"
          >
            <el-option
              v-for="shop in shopList"
              :key="shop.id"
              :label="`${shop.shopName} (${shop.shopCode})`"
              :value="shop.id"
            />
          </el-select>
          <div class="selected-shops-info" v-if="formData.shopIds.length > 0">
            <el-tag
              v-for="shopId in formData.shopIds"
              :key="shopId"
              closable
              @close="removeShop(shopId)"
              class="shop-tag"
            >
              {{ getShopName(shopId) }}
            </el-tag>
          </div>
        </div>
      </el-form-item>

      <!-- 费用类型选择 -->
      <el-form-item label="费用类型" prop="feeType" required>
        <el-select
          v-model="formData.feeType"
          placeholder="请选择费用类型"
          style="width: 200px"
          @change="handleFeeTypeChange"
        >
          <el-option label="物业费" value="PROPERTY" />
          <el-option label="水费" value="WATER" />
          <el-option label="电费" value="ELECTRIC" />
          <el-option label="燃气费" value="GAS" />
          <el-option label="卫生费" value="SANITATION" />
        </el-select>
      </el-form-item>

      <!-- 费用标准设置 -->
      <el-form-item label="费用标准" prop="feeAmount" required>
        <div class="fee-amount-input">
          <el-input-number
            v-model="formData.feeAmount"
            :min="0"
            :precision="2"
            placeholder="请输入费用标准"
            style="width: 200px"
          />
          <span class="unit-text">{{ getFeeUnit() }}</span>
        </div>
      </el-form-item>

      <!-- 生效日期 -->
      <el-form-item label="生效日期" prop="effectiveDate" required>
        <el-date-picker
          v-model="formData.effectiveDate"
          type="date"
          placeholder="请选择生效日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>

      <!-- 失效日期（可选） -->
      <el-form-item label="失效日期">
        <el-date-picker
          v-model="formData.expiryDate"
          type="date"
          placeholder="请选择失效日期（可选）"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>

      <!-- 状态设置 -->
      <el-form-item label="状态" prop="status" required>
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 预览区域 -->
    <div class="preview-area" v-if="formData.shopIds.length > 0 && formData.feeType">
      <el-divider content-position="left">批量设置预览</el-divider>
      <div class="preview-content">
        <el-alert
          :title="`将为 ${formData.shopIds.length} 个店铺设置 ${getFeeTypeName()} 费用标准`"
          type="info"
          :closable="false"
          show-icon
        />
        <div class="preview-list">
          <el-table :data="previewData" size="small" border>
            <el-table-column prop="shopName" label="店铺名称" width="150" />
            <el-table-column prop="feeTypeName" label="费用类型" width="100" />
            <el-table-column prop="feeAmount" label="费用标准" width="120">
              <template #default="{ row }">
                <span class="money-text">¥{{ row.feeAmount.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="effectiveDate" label="生效日期" width="120" />
            <el-table-column prop="expiryDate" label="失效日期" width="120">
              <template #default="{ row }">
                {{ row.expiryDate || '长期' }}
              </template>
            </el-table-column>
            <el-table-column prop="statusName" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ row.statusName }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确认批量设置
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { ShopDetail } from '@/api/shop'
import { shopApi } from '@/api/shop'
import { shopFeeStandardApi, type BatchCreateFeeStandardDTO } from '@/api/region/shop-fee-standard'

// Props
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const shopList = ref<ShopDetail[]>([])
const loading = ref(false)

// 表单数据
const formData = reactive({
  shopIds: [] as number[],
  feeType: undefined as string | undefined,
  feeAmount: undefined as number | undefined,
  effectiveDate: undefined as string | undefined,
  expiryDate: undefined as string | undefined,
  status: 1 as number,
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  shopIds: [
    { required: true, message: '请选择至少一个店铺', trigger: 'change' }
  ],
  feeType: [
    { required: true, message: '请选择费用类型', trigger: 'change' }
  ],
  feeAmount: [
    { required: true, message: '请输入费用标准', trigger: 'blur' },
    { type: 'number', min: 0, message: '费用标准不能小于0', trigger: 'blur' }
  ],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const previewData = computed(() => {
  if (formData.shopIds.length === 0 || !formData.feeType) {
    return []
  }
  
  return formData.shopIds.map(shopId => {
    const shop = shopList.value.find(s => s.id === shopId)
    return {
      shopName: shop ? `${shop.shopName} (${shop.shopCode})` : '',
      feeTypeName: getFeeTypeName(),
      feeAmount: formData.feeAmount || 0,
      effectiveDate: formData.effectiveDate || '',
      expiryDate: formData.expiryDate || '',
      status: formData.status,
      statusName: formData.status === 1 ? '启用' : '禁用'
    }
  })
})

// 方法
const loadShopList = async () => {
  loading.value = true
  try {
    // 调用真实API获取店铺列表
    const response = await shopApi.getShopPage({
      current: 1,
      size: 1000, // 获取所有店铺
      status: 1 // 只获取启用的店铺
    })
    
    if (response && response.code === 200 && response.data) {
      // 过滤掉没有有效id的数据，遵循Element Plus组件编码规范
      shopList.value = (response.data.records || []).filter((item: any) => item.id != null)
      console.log('店铺列表加载成功:', shopList.value.length, '个店铺')
    } else {
      ElMessage.error(response?.message || '加载店铺列表失败')
      shopList.value = []
    }
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
    shopList.value = []
  } finally {
    loading.value = false
  }
}

const handleShopChange = (shopIds: number[]) => {
  formData.shopIds = shopIds
}

const removeShop = (shopId: number) => {
  const index = formData.shopIds.indexOf(shopId)
  if (index > -1) {
    formData.shopIds.splice(index, 1)
  }
}

const getShopName = (shopId: number) => {
  const shop = shopList.value.find(s => s.id === shopId)
  return shop ? `${shop.shopName} (${shop.shopCode})` : ''
}

const handleFeeTypeChange = (feeType: string) => {
  formData.feeType = feeType
}

const getFeeTypeName = () => {
  const typeMap = {
    'PROPERTY': '物业费',
    'WATER': '水费',
    'ELECTRIC': '电费',
    'GAS': '燃气费',
    'SANITATION': '卫生费'
  }
  return typeMap[formData.feeType as keyof typeof typeMap] || ''
}

const getFeeUnit = () => {
  const unitMap = {
    'PROPERTY': '元/㎡/月',
    'WATER': '元/吨',
    'ELECTRIC': '元/度',
    'GAS': '元/立方米',
    'SANITATION': '元/㎡/月'
  }
  return unitMap[formData.feeType as keyof typeof unitMap] || ''
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 构建请求数据，遵循《Element Plus组件编码规范权威标准声明.md》规范
    const requestData: BatchCreateFeeStandardDTO = {
      shopIds: formData.shopIds,
      feeType: formData.feeType!,
      feeAmount: formData.feeAmount!,
      feeUnit: getFeeUnit(),
      effectiveDate: formData.effectiveDate!,
      expiryDate: formData.expiryDate,
      status: formData.status,
      remark: formData.remark
    }
    
    // 调用真实API
    const response = await shopFeeStandardApi.batchCreate(requestData)
    
    if (response && response.code === 200) {
      ElMessage.success(`成功为 ${formData.shopIds.length} 个店铺设置费用标准`)
      emit('success')
      handleClose()
    } else {
      ElMessage.error(response?.message || '批量设置费用标准失败')
    }
  } catch (error) {
    console.error('批量设置费用标准失败:', error)
    ElMessage.error('批量设置费用标准失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    shopIds: [],
    feeType: undefined,
    feeAmount: undefined,
    effectiveDate: undefined,
    expiryDate: undefined,
    status: 1,
    remark: ''
  })
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal) {
    loadShopList()
  }
})
</script>

<style scoped>
.batch-form {
  max-height: 60vh;
  overflow-y: auto;
}

.shop-selection-area {
  width: 100%;
}

.selected-shops-info {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.shop-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.fee-amount-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-text {
  color: #606266;
  font-size: 14px;
}

.preview-area {
  margin-top: 20px;
}

.preview-content {
  margin-top: 16px;
}

.preview-list {
  margin-top: 12px;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  font-size: 12px;
}

:deep(.el-table .el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-alert) {
  margin-bottom: 12px;
}
</style>
